use std::sync::Arc;

use thunderdome::Index;
use QcUI::component::Canvas;

use crate::{
    components::nestable::ItemTrait,
    core::{context::Context, message::ObjectType},
};

#[derive(Hash, Clone, Copy, PartialEq, Eq, Debug)]
pub struct LayerItem {
    pub id: Index,
    pub obj_type: ObjectType,
}

impl ItemTrait for LayerItem {
    fn new(index: Index) -> Self {
        Self {
            id: index,
            obj_type: ObjectType::GameObject,
        }
    }

    fn get_id(&self) -> Index {
        self.id
    }

    fn get_egui_id(&self) -> egui::Id {
        let id = format!("ID{:?}Type{:?}", self.id, self.obj_type);
        egui::Id::new(id)
    }

    fn get_string(&self, context: Arc<Context>) -> String {
        let scene_manager = context.scene_manager.try_read().unwrap();
        let scene = scene_manager.get_current_scene().unwrap();

        match self.obj_type {
            ObjectType::GameObject => {
                let obj = &scene[self.id];

                obj.getName().to_owned()
            }
            ObjectType::UiObject => {
                if let Some(canvas_id) = scene.get_main_canvas() {
                    if let Some(canvas) = scene[canvas_id].getComponent::<Canvas>() {
                        let widget = canvas[self.id].get_widget();

                        return widget.name.clone();
                    }
                }

                String::from("UiNode")
            }
        }
    }
}

impl Default for LayerItem {
    fn default() -> Self {
        Self {
            id: Index::DANGLING,
            obj_type: ObjectType::GameObject,
        }
    }
}

impl LayerItem {
    pub fn with_type(mut self, obj_type: ObjectType) -> Self {
        self.obj_type = obj_type;
        self
    }
}
